/*
 * @Author: yanjikun
 * @Date: 2022-05-12 15:11:04
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-05-12 15:59:35
 * @Description: file content
 */

import { error } from '@/utils/log'
import { isEmpty } from 'lodash'
import { nextTick, onMounted, Ref, ref, SetupContext, unref, watch } from 'vue'
import BasicDescriptions from '../..'
import { BasicDescriptionsInstance, BasicDescriptionsProps } from '../basic-descriptions'

export const useDescriptions = (props?: BasicDescriptionsProps) => {
  const descRef = ref<BasicDescriptionsInstance>({})
  const getDescInstance = async () => {
    await nextTick()
    const desc = unref(descRef)
    if (isEmpty(desc)) {
      error('未获取到descriptions示例！')
    }
    return desc
  }

  watch(
    () => props,
    () => {
      props &&
        onMounted(async () => {
          ;(await getDescInstance())?.setProps(props)
        })
    },
    { immediate: true, deep: true },
  )

  const methods = new Proxy<Ref<BasicDescriptionsInstance>>(descRef, {
    get(target, key) {
      if (Reflect.has(target, key)) {
        return unref(target)
      }
      if (Reflect.has(target.value, key)) {
        return target.value[key]
      }
      return async (...rest) => {
        const table = await getDescInstance()
        table?.[key](...rest)
      }
    },
  })

  const DescRender = (
    comProps: Partial<BasicDescriptionsProps>,
    { attrs, slots }: SetupContext,
  ) => {
    return (
      <BasicDescriptions
        ref={descRef}
        {...{ ...attrs, ...props, ...comProps }}
        v-slots={slots}
      ></BasicDescriptions>
    )
  }
  return [DescRender, unref(methods)] as const
}
